package com.one.blocks.rbac.controller.valid;

import com.one.blocks.rbac.controller.vo.SysOrgVo;
import com.one.blocks.rbac.domain.SysOrg;
import com.one.blocks.rbac.manager.SysOrgManager;
import com.one.blocks.rbac.manager.SysRoleOrgManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author linfuxin Created on 2022-08-16 17:41:36
 */
@Slf4j
public class ValidTreeValidatorForSysOrg implements ConstraintValidator<ValidTree, SysOrgVo> {

    @Autowired
    private SysOrgManager sysOrgManager;

    @Autowired
    private SysRoleOrgManager sysRoleOrgManager;

    @Override
    public boolean isValid(SysOrgVo value, ConstraintValidatorContext context) {
        SysOrg oldData = sysOrgManager.get(value.getId());
        if (!oldData.getParentId().equals(value.getParentId())) {
            // 校验是否存在关联数据
            Integer[] existsDataKeys = sysRoleOrgManager.existsDataByKeys(value.getId());
            if (log.isDebugEnabled() && ArrayUtils.isNotEmpty(existsDataKeys)) {
                log.debug("关联数据:{}", existsDataKeys[0]);
            }
            return ArrayUtils.isEmpty(existsDataKeys);
        }
        return false;
    }
}
